package com.ruoyi.project.weixin.mp.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.framework.web.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.menu.WxMpMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * 微信公众号菜单管理
 * 官方文档：https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Creating_Custom-Defined_Menu.html
 * WxJava开发文档：https://github.com/Wechat-Group/WxJava/wiki/MP_自定义菜单管理
 */
@RestController
@RequestMapping("/manage/wxMenu")
@RequiredArgsConstructor
@Api(tags = {"公众号菜单-管理后台"})
public class WxMenuController {

    private final WxMpService wxService;

    @Autowired
    private WxMpService wxMpService;

    /**
     * 获取公众号菜单
     */
    @GetMapping("/getMenu")
    @ApiOperation(value = "获取公众号菜单")
    public AjaxResult getMenu(@RequestParam String appid) throws WxErrorException {
        wxMpService.switchoverTo(appid);
        WxMpMenu wxMpMenu = wxService.getMenuService().menuGet();
        return AjaxResult.success(wxMpMenu);
    }

    /**
     * 创建、更新菜单
     */
    @PostMapping("/updateMenu")
    @PreAuthorize("@ss.hasPermi('wx:menu:save')")
    @ApiOperation(value = "创建、更新菜单")
    public AjaxResult updateMenu(@RequestBody JSONObject obj) throws WxErrorException { //, @RequestBody(required = false) WxMenu wxMenu
        String appid = obj.getString("appid");
        wxMpService.switchoverTo(appid);
        WxMenu wxMenu = obj.getObject("wxMenu", WxMenu.class);
        wxService.getMenuService().menuCreate(wxMenu);
        return AjaxResult.success();
    }

}
